//
//  LYQHomeViewController.swift
//  SwiftWeibo
//
//  Created by 刘英群 on 2016/12/22.
//  Copyright © 2016年 刘英群. All rights reserved.
//

import UIKit

// 定义全局常量，尽量使用private修饰，否则到处都可以访问
// 原创微博可重用cellId
fileprivate let originalCellId = "originalCellId"
// 被转发微博的可重用cellID
fileprivate let retweetedCellId = "retweetedCellId"

class LYQHomeViewController: LYQBaseViewController {

    //列表视图模型
    fileprivate lazy var listViewModel = LYQStatusListViewModel()
    

    //加载数据
    override func loadData() {
        
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
            
        
//         print("准备刷新，最后一条\(self.listViewModel.statusList.last?.text)")
        self.listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldrefresh) in
            
            print("加载数据结束")
            //结束刷新控件
            self.refreshControl?.endRefreshing()
            
            //恢复上拉刷新标记
            self.isPullup = false
            
            //刷新表格
            
            if shouldrefresh {
                self.tableView?.reloadData()
            }
        }
        }
    }
    
    //显示好友
    @objc fileprivate func showFriends() {
        print(#function)
        let vc = LYQDemoViewController()
        
        // push的动作是nav做的
        navigationController?.pushViewController(vc, animated: true)
    }
}

// MARK: - 表格数据源方法, 具体的数据源方法实现
extension LYQHomeViewController {
 
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return listViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // 0.取出视图模型， 根据视图模型判断可重用cell
        let vm = listViewModel.statusList[indexPath.row]
        
        let cellId = (vm.status.retweeted_status == nil) ? retweetedCellId : originalCellId
        
        //1.取cell - 本身会调用代理方法（如果有），如果没有，找到cell，按照自动布局的规划，从上向下计算，找到向下的约束，从而计算动态行高
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! LYQStatusCell
        //2.设置cell
        cell.viewModel = vm
        
        //3.返回cell
        return cell
    }
    
    // 父类必须实现代理方法，子类才能够重写
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        // 1.根据indexPath获取视图模型
        let vm = listViewModel.statusList[indexPath.row]
        
        // 2.返回计算好的行高
        return vm.rowHeight
    }
}


// MARK: - 设置界面
extension LYQHomeViewController {
    
    // 重写父类方法
    override func setupTableView() {
        
        super.setupTableView()
        
        //设置导航栏按钮
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", target: self, action: #selector(showFriends))
        
        //注册cell
//        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        
        tableView?.register(UINib(nibName: "LYQStatusNormalCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        tableView?.register(UINib(nibName: "LYQStatusRetweetedCell", bundle: nil), forCellReuseIdentifier: retweetedCellId)
        
        //设置行高
//        tableView?.rowHeight = UITableViewAutomaticDimension
        tableView?.estimatedRowHeight = 300
        
        //取消分割线
        tableView?.separatorStyle = .none
        
        setupNavTitle()
    }
    
    //设置导航栏标题
    fileprivate func setupNavTitle(){
    
        let title = LYQNetworkManager.shared.userAccount.screen_name

        let button = LYQWBButton(title: title)
        
        navItem.titleView = button
        
        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
    }
    
    @objc func clickTitleButton(btn: UIButton) {
        
        btn.isSelected = !btn.isSelected
    }
}

//下面这种方法无法高亮
//        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", style: .plain, target: self, action: #selector(showFriends))

//Swift调用 OC 返回 instanceType的方法， 判断不出是否可选
//        let btn: UIButton = UIButton.cz_textButton("好友", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.orange)
//        btn.addTarget(self, action: #selector(showFriends), for: .touchUpInside)
//        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
